package com.bestcem.xm.qdes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bestcem.xm.component.mybatis.service.impl.XmServiceImpl;
import com.bestcem.xm.qdes.controller.param.ImageLibPageParam;
import com.bestcem.xm.qdes.controller.vo.DeletedCountVo;
import com.bestcem.xm.qdes.controller.vo.ImagelibVo;
import com.bestcem.xm.qdes.entity.QdesImageLib;
import com.bestcem.xm.qdes.entity.UploadFileMap;
import com.bestcem.xm.qdes.mapper.QdesImageLibMapper;
import com.bestcem.xm.qdes.mapper.UploadFileInfoMapper;
import com.bestcem.xm.qdes.mapper.UploadFileMapMapper;
import com.bestcem.xm.qdes.service.QdesImageLibService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Service
@RequiredArgsConstructor
public class QdesImageLibServiceImpl extends XmServiceImpl<QdesImageLibMapper, QdesImageLib> implements QdesImageLibService {

    private @NonNull UploadFileMapMapper uploadFileMapMapper;

    private @NonNull UploadFileInfoMapper uploadFileInfoMapper;

    @Override
    public Page<ImagelibVo> pageImagelib(Page<ImagelibVo> page, ImageLibPageParam param) {
        Page<ImagelibVo> pages = baseMapper.pageImagelibPage(page, param);
        return pages;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeletedCountVo deleteImagelib(String id) {
        QdesImageLib qdesImagelib = baseMapper.selectById(id);
        //1.删除imagelib
        DeletedCountVo deletedCountVo = new DeletedCountVo();
        int count = baseMapper.deleteById(id);
        if (count != 0) {
            //2.删除upload_filemap,先查询对应的fileinfoId，后续判断是否删除fileinfo
            UploadFileMap uploadFileMap = uploadFileMapMapper.selectById(qdesImagelib.getFilemapId());
            //创建修改条件对象
            LambdaQueryWrapper<UploadFileMap> queryWrapper = new LambdaQueryWrapper<>();
            //构造查询条件
            queryWrapper
                    .eq(UploadFileMap::getFileInfoId, uploadFileMap.getFileInfoId())
                    .eq(UploadFileMap::getDeleted, 0);
            long countFileMap = uploadFileMapMapper.selectCount(queryWrapper);

            uploadFileMapMapper.deleteById(qdesImagelib.getFilemapId());
            if (countFileMap == 1) {
                //需要删除upload_fileinfo
                uploadFileInfoMapper.deleteById(uploadFileMap.getFileInfoId());
            }
            deletedCountVo.setDeletedCount(1);
        } else {
            deletedCountVo.setDeletedCount(0);
        }
        return deletedCountVo;
    }

}
